package com.sunday.common.mq.kafka.study.spring.e8_Transactions;

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.core.ProducerFactory;
import org.springframework.kafka.support.SendResult;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * {@link org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration}
 * 开启事务 需要在 yaml中设置 transaction-id-prefix: ${spring.application.name}
 * 因为 starter要使用
 *
 * @Bean
 * @ConditionalOnProperty(name = "spring.kafka.producer.transaction-id-prefix")
 * @ConditionalOnMissingBean public KafkaTransactionManager<?, ?> kafkaTransactionManager(ProducerFactory<?, ?> producerFactory) {
 * return new KafkaTransactionManager<>(producerFactory);
 * }
 */
@Slf4j
@RestController
@RequestMapping("/test")
public class MQApi implements InitializingBean {

    @Autowired
    private KafkaTemplate<Object, Object> kafkaTemplate;

    @Override
    public void afterPropertiesSet() throws Exception {
        ProducerFactory<Object, Object> producerFactory = kafkaTemplate.getProducerFactory();
        producerFactory.updateConfigs(Map.of(
//                ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, true,
                ProducerConfig.RETRIES_CONFIG, 1
        ));
    }

    @GetMapping("/send/{topic}/{key}")
    public void send(@PathVariable String topic, @PathVariable String key) {
        CompletableFuture<SendResult<Object, Object>> future;
        future = kafkaTemplate.executeInTransaction(callback -> {
            CompletableFuture<SendResult<Object, Object>> temp = callback.send(topic, key, key);
//            try {
            int i = 1 / 0;
//            } catch (Exception e){
//                log.error("{}", e.toString());
//            }
            return temp;
        });
        future.whenComplete((result, throwable) -> log.info("[{}] result : {}, throwable : {}", topic, result, throwable));
    }

    @GetMapping("/batch/{topic}")
    @Transactional(rollbackFor = Exception.class)
    public void batch(@PathVariable String topic) throws Exception {
        CompletableFuture<SendResult<Object, Object>> future;
        for (int i = 0; i < 10; i++) {
            future = kafkaTemplate.send(topic, i + "", i + "");
            future.whenComplete((result, throwable) -> log.info("[{}] result : {}, throwable : {}", topic, result, throwable));
        }
        throw new Exception("transaction rollback");
    }

    @KafkaListener(
            id = "myId_6",
            topics = "topic6",
            clientIdPrefix = "TEST"
    )
    public void listen6(String in) {
        log.info("======================== {}", in);
    }


}
